package com.example.readroomforpaging3.paging

import androidx.paging.PagingSource
import com.example.readroomforpaging3.model.Article
import com.example.readroomforpaging3.network.NetworkCreator
import retrofit2.HttpException
import java.io.IOException

class ArticleRemoteDataSource: PagingSource<Int, Article>() {

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Article> {
        return try {
            val page = params.key ?: 0
            //获取网络数据
            val result = NetworkCreator.getArticlePage(page)
            LoadResult.Page(
                    //需要加载的数据
                    data = result.datas,
                    //如果可以往上加载更多就设置该参数，否则不设置
                    prevKey = null,
                    //加载下一页的key 如果传null就说明到底了
                    nextKey = if (result.curPage == result.pageCount) null else page + 1
            )
        } catch (e: IOException) {
            // IOException for network failures.
            return LoadResult.Error(e)
        } catch (e: HttpException) {
            // HttpException for any non-2xx HTTP status codes.
            return LoadResult.Error(e)
        }
    }
}